var gulp = require('gulp');
var gutil = require("gulp-util");
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var tsify = require('tsify');
var watchify = require("watchify");
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');
var paths = {
    pages: ['src/*.html'],
    entries: ['src/index.ts'],
    output: 'build'
};

var watchedBrowserify = watchify(browserify({
    basedir: '.',
    debug: true,
    entries: paths.entries,
    cache: {},
    packageCache: {}
}).plugin(tsify));


function bundle() {
    return watchedBrowserify
        .transform('babelify', {
            presets: ['es2015'],
            extensions: ['.ts']
        })
        .bundle()
        .pipe(source('index.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('build'));
}

gulp.task('copy-html', function () {
    return gulp.src(paths.pages)
        .pipe(gulp.dest('build'));
});

gulp.task("default", ["copy-html"], bundle);

watchedBrowserify.on("update", bundle);
watchedBrowserify.on("log", gutil.log);
